package dfbz.com.controller.view;

import dfbz.com.controller.BaseServlet;
import dfbz.com.controller.dept.DeptServlet;
import dfbz.com.model.*;
import dfbz.com.service.AritcleService;
import dfbz.com.service.DeptService;
import dfbz.com.service.MeetingService;
import dfbz.com.service.UserService;
import dfbz.com.service.impl.ArticleServiceImp;
import dfbz.com.service.impl.DeptServiceImp;
import dfbz.com.service.impl.MeetingServiceImp;
import dfbz.com.service.impl.UserServiceImp;
import dfbz.com.utils.PageUtil;
import dfbz.com.utils.TranslateUtil;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;


@WebServlet("/view/*")
public class UIServlet extends BaseServlet {

    private UserService userService = new UserServiceImp();
    private AritcleService aritcleService = new ArticleServiceImp();
    private ArticleServiceImp articleService = new ArticleServiceImp();
    private DeptService deptService = new DeptServiceImp();
    private MeetingService meetingService = new MeetingServiceImp();


    public void home(HttpServletRequest req, HttpServletResponse resp) {


        try {
            req.getRequestDispatcher("/html/home.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void user(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher("/html/user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void userLook(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String userId = req.getSession().getAttribute("userId").toString();
//            查找登录用户的关注数
            Integer count = userService.findMyFocusCount(userId);
            req.setAttribute("myFocusCount", count);
//            查找所有部门
            List<Dept> dept = deptService.findAllDept();
            //System.out.println(dept);
            req.getSession().setAttribute("deptList", dept);


            req.getRequestDispatcher("/html/user_look.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void myUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher("/html/my_user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void index(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void userDetail(HttpServletRequest req, HttpServletResponse resp) {

        String uId = req.getParameter("uId");
        String userId = req.getSession().getAttribute("userId").toString();
//        System.out.println("view中------"+uId);

//       如果查看的不是用户自己的信息，将look加一
        if (!userId.equals(uId)) {
            userService.addLook(uId);
        }

//        根据被查看的用户id找他的粉丝数
        Integer count = userService.findFocusCount(uId);
        req.setAttribute("focusCount", count);

        Map userDetail = userService.findUserDetailInfo(uId);

//        System.out.println("detail:" + userDetail);
//        req.getSession().setAttribute("userDetail", userDetail);
        req.setAttribute("userDetail", userDetail);

        try {
            req.getRequestDispatcher("/html/user_detail.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 分页
     *
     * @param req
     * @param resp
     */

    public void userPage(HttpServletRequest req, HttpServletResponse resp) {
        String current = req.getParameter("current");
        String search = req.getParameter("search");

        Integer userId = (Integer) req.getSession().getAttribute("userId");
        if (current == null) {
            current = "1";
        }
        //这里的参数应该是从user重定向设置的参数
        if (null != search) {
            try {
//                为什么要用这种编码
                search = URLDecoder.decode(search, "UTF-8");
                byte[] bytes = search.getBytes("ISO-8859-1");
                search = new String(bytes, "UTF-8");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        System.out.println("view里的current和search：" + current + ":" + search);
        //返回的是user按分页查询的信息列表
        List<Map<String, Object>> list = userService.showUserByPage(userId, current, search);
//        System.out.println("返回的list："+list);
        req.setAttribute("pageUser", list);

        //查找搜索到的总信息数
        long listTotalCount = userService.findTotalCount(search);
        //System.out.println("找到的总信息数："+listTotalCount);
        //分页查询的查询按钮有多少个
        long totalPage = PageUtil.getTotalPage(listTotalCount);
        //System.out.println("计算后的总页数："+totalPage);
        req.setAttribute("totalPage", totalPage);
//        记得设置回搜索信息，不然跳转页面后找不到这个信息
        req.setAttribute("current", Integer.parseInt(current));
        req.setAttribute("search", search);

        try {
            req.getRequestDispatcher("/html/user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void forget(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher("/forget.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void register(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //去除显示在页面上的错误信息
//        req.getSession().removeAttribute("registerError");
//        Object mag = req.getSession().getAttribute("registerError");
//        System.out.println("删除错误信息后："+mag);
    }


    public void article(HttpServletRequest req, HttpServletResponse resp) {

        String current = req.getParameter("current");
        String articleName = req.getParameter("articleName");
        if (articleName != null) {
            try {
                articleName = URLDecoder.decode(articleName, "UTF-8");
                byte[] bytes = articleName.getBytes("ISO-8859-1");
                articleName = new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        //查找文章列表
        List<Article> articleList = aritcleService.findArticleList(current, articleName);
//        System.out.println("看这里-------------"+articleList);
        req.setAttribute("articleList", articleList);
        //总共查询到几条记录
        Long total = aritcleService.findTotalCount(articleName);
        long totalPage = PageUtil.getTotalPage(total);
        req.setAttribute("articleTotalCount", totalPage);
        req.setAttribute("articleName", articleName);
        req.setAttribute("current", current);
        try {
            req.getRequestDispatcher("/html/article.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void articleAdd(HttpServletRequest req, HttpServletResponse resp) {
        try {


            req.getRequestDispatcher("/html/article_add.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void department(HttpServletRequest req, HttpServletResponse resp) {

        List list = deptService.findDeptMsg();
        req.setAttribute("dept", list);
        try {
            req.getRequestDispatcher("/html/department.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void meeting(HttpServletRequest req, HttpServletResponse resp) {

        String dep = req.getParameter("dep");
        String title = req.getParameter("title");
        String current = req.getParameter("current");
        try {
//            System.out.println("-------------------------");
//            System.out.println("view中的参数：");
//            System.out.println(dep);
//            System.out.println(title);

//           URL编码注意空指针异常
            if (dep != null) {
                dep = TranslateUtil.translateStr(dep);
                // System.out.println("view中编译后的dep："+dep);
            }

            if (title != null) {
                title = TranslateUtil.translateStr(title);
                //System.out.println("view中编译后的title："+title);

            }
//            搜索框的部门信息展示
            Object deptList = req.getSession().getAttribute("deptList");
            if (deptList == null) {
                List<Dept> allDept = deptService.findAllDept();
                req.getSession().setAttribute("deptList", allDept);
            }

            List list = meetingService.showMeetingList(current, dep, title);
            req.setAttribute("meetingList", list);
//            System.out.println("------------------------");
//            System.out.println("拿到的list："+list);

            long totalCount = meetingService.findTotalCount(dep, title);
            long totalPage = PageUtil.getTotalPage(totalCount);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("title", title);
            req.setAttribute("dep", dep);

            req.getRequestDispatcher("/html/meeting.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void meetingDetail(HttpServletRequest req, HttpServletResponse resp) {

        String meetingId = req.getParameter("meetingId");
        try {
            //根据id找到这个会议
            Conference con = meetingService.findMeetingDetail(meetingId);
            req.setAttribute("conDetail", con);
//            System.out.println(con);
            Integer deptId = con.getDeptId();
//            根据这个会议的部门id找到该部门总人数
            Long total = meetingService.findTotalMemberCount(deptId);
            req.setAttribute("total", total);
//            根据会议id去con_join找到未到人数(状态为0的)
            Integer count = meetingService.findAbsentCount(meetingId);
            req.setAttribute("absent",count);
//            计算实到人数
            req.setAttribute("attend",total-count);

            req.getRequestDispatcher("/html/meeting_detail.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 参加会议，相当于打卡功能，重新刷新页面
     *
     * @param req
     * @param resp
     */
    public void meetingAdd(HttpServletRequest req, HttpServletResponse resp) {

        //统计人数（应到--总数，实际到--打卡人数）

        try {
            req.getRequestDispatcher("/html/meeting_add.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void articleCollect(HttpServletRequest req, HttpServletResponse resp) {


        try {
            String current = req.getParameter("current");
            String articleName = req.getParameter("articleName");
            Integer userId = (Integer) req.getSession().getAttribute("userId");
            if (articleName != null) {
                try {
                    articleName = URLDecoder.decode(articleName, "UTF-8");
                    byte[] bytes = articleName.getBytes("ISO-8859-1");
                    articleName = new String(bytes, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            //查找文章列表
            List articleList = articleService.findCollectArticleList(current, articleName, userId.toString());
            // List<Article> articleList = aritcleService.findArticleList(current, articleName);
//            System.out.println("收藏的文章-----------："+articleList);
            req.setAttribute("articleList", articleList);
            Long total = articleService.findCollectTotalCount(articleName, userId.toString());
            long totalPage = PageUtil.getTotalPage(total);
            req.setAttribute("articleTotalCount", totalPage);
            req.setAttribute("articleName", articleName);
            req.setAttribute("current", current);
            req.getRequestDispatcher("/html/article_collect.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void articleDetail(HttpServletRequest req, HttpServletResponse resp) {

        String bookId = req.getParameter("bookId");
        Object userId = req.getSession().getAttribute("userId");
        Integer uId = Integer.parseInt(userId.toString());
        Integer aId = Integer.parseInt(bookId);
//        点击查看时先将浏览数加一再存进去
        articleService.updateBrowseCount(aId);

        Map article = articleService.findArticleDetail(bookId);
//        System.out.println("看这里-------"+article);
//        判断用户是否收藏过该文章
        Integer flag = articleService.ifCollect(aId, uId);
        req.setAttribute("ifCollect", flag);

//       查找关注的人中收藏了这篇文章的人
        List list = articleService.findCoCollectPeople(aId, uId);
        req.setAttribute("coCollect", list);

        req.setAttribute("article", article);
        try {
            req.getRequestDispatcher("/html/article_detail.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
